package com.youlu.campus.service.douyin;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : [dengbo]
 * @className : ThirdTokenStoreService
 * @description : [三方token存储]
 * @createTime : [2023/3/1 10:17]
 */
@Service
@Slf4j
public class ThirdTokenStoreService {
    public static String ACCESS_TOKEN_PRE_FIX = "campus:access:token:appId:%s";

    public static String SESSION_KEY_PRE_FIX = "com.luyou.session-key.appId:%s.openId:%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String getSessionKey(final String appId, final String openId) {
        Object v = stringRedisTemplate.opsForValue().get(getSessionKeyK(appId, openId));
        if (Objects.isNull(v)) {
            return null;
        }
        return v.toString();
    }

    public void setSessionKey(final String appId, final String openId, final String sessionKey) {

        stringRedisTemplate.opsForValue().set(getSessionKeyK(appId, openId), sessionKey, 30, TimeUnit.DAYS);
    }

    private String getSessionKeyK(final String appId, final String openId) {
        log.info("third session key appId:{},openId:{} sessionKey k:{}", appId, openId, String.format(SESSION_KEY_PRE_FIX, appId, openId));
        return String.format(SESSION_KEY_PRE_FIX, appId, openId);
    }

    public String getAccessToken(final String appId) {
        String accessTokenK = getAccessTokenK(appId);
        return stringRedisTemplate.opsForValue().get(accessTokenK);
    }

    public void setAccessToken(final String appId, final String accessToken, final Integer expiresIn) {
        String accessTokenK = getAccessTokenK(appId);
        stringRedisTemplate.opsForValue().set(accessTokenK, accessToken, expiresIn, TimeUnit.SECONDS);
    }

    private String getAccessTokenK(final String appId) {
        log.info("third session key appId:{},openId:{} sessionKey k:{}", appId, String.format(ACCESS_TOKEN_PRE_FIX, appId));
        return String.format(ACCESS_TOKEN_PRE_FIX, appId);
    }

    /**
     * 判断key是否存在
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }
}
